package by.amakarevich.dataaccess.Impl;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaDelete;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;

import org.hibernate.jpa.criteria.OrderImpl;
import org.springframework.stereotype.Repository;

import by.amakarevich.dataaccess.DeliveryAddressDao;
import by.amakarevich.datamodel.Booking;
import by.amakarevich.datamodel.DeliveryAddress;
import by.amakarevich.datamodel.DeliveryAddress_;

@Repository
public class DeliveryAddressDaoImpl extends AbstractDaoImpl<Long, DeliveryAddress> implements DeliveryAddressDao  {
	protected DeliveryAddressDaoImpl(){
		super(DeliveryAddress.class);
	}
	
	@Override
    public List<DeliveryAddress> getAllDeliveryAddressByUser(SingularAttribute<DeliveryAddress, ?> attr, boolean ascending, int startRecord, int pageSize) {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

        CriteriaQuery<DeliveryAddress> criteria = cBuilder.createQuery(DeliveryAddress.class);
        Root<DeliveryAddress> root = criteria.from(DeliveryAddress.class);

        criteria.select(root);
        criteria.orderBy(new OrderImpl(root.get(attr), ascending));

        TypedQuery<DeliveryAddress> query = getEm().createQuery(criteria);
        query.setFirstResult(startRecord);
        query.setMaxResults(pageSize);

        List<DeliveryAddress> results = query.getResultList();
        return results;
    }
	

       
	@Override
    public void deleteDeliveryAddress(Long id) {
        CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

        CriteriaDelete<DeliveryAddress> root = cBuilder.createCriteriaDelete(DeliveryAddress.class);
        Root<DeliveryAddress> criteria = root.from(DeliveryAddress.class);


        root.where(cBuilder.equal(criteria.get("id"), id));

        getEm().createQuery(root).executeUpdate();
	}
	
	@Override
	public DeliveryAddress getByBooking(Booking booking){
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();
		CriteriaQuery<DeliveryAddress> criteria = cBuilder
				.createQuery(DeliveryAddress.class);
		Root<DeliveryAddress> root = criteria.from(DeliveryAddress.class);

		criteria.select(root);
		criteria.where(cBuilder.equal(root.get(DeliveryAddress_.booking),
				booking.getId()));

		TypedQuery<DeliveryAddress> query = getEm().createQuery(criteria);
		DeliveryAddress result = (DeliveryAddress) query.getSingleResult();
		return result;
	}
}
